// DriveNotes. Copyright (c) 2011, Andrei Senchuk. All rights reserved.
package net.taviscaron.drivenotes.server.service;

import java.util.List;
import net.taviscaron.drivenotes.server.model.dao.CarDAO;
import net.taviscaron.drivenotes.server.model.validators.Validator;
import net.taviscaron.drivenotes.server.util.EntityUtils;
import net.taviscaron.drivenotes.shared.exceptions.InvalidEntityException;
import net.taviscaron.drivenotes.shared.model.entity.Car;
import net.taviscaron.drivenotes.shared.model.entity.User;
import net.taviscaron.drivenotes.shared.service.GarageService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.transaction.annotation.Transactional;

/**
 * Garage service impl
 * @author Andrei Senchuk
 */
public class GarageServiceImpl implements GarageService {
    private static final Log logger = LogFactory.getLog(GarageServiceImpl.class);
    private Validator<Car> carValidator;
    private CarDAO carDAO;

    @Required
    public void setCarValidator(Validator<Car> carValidator) {
        this.carValidator = carValidator;
    }

    @Required
    public void setCarDAO(CarDAO carDAO) {
        this.carDAO = carDAO;
    }

    @Transactional
    public List<Car> findCarsByOwnerId(Long ownerId) {
        List<Car> cars = carDAO.findByOwnerId(ownerId);
        for(int i = 0; i < cars.size(); i++) {
            cars.set(i, EntityUtils.createCarValueObject(cars.get(i)));
        }
        return cars;
    }

    @Transactional
    public Car findCar(Long carId, User owner) {
        Car car = carDAO.findByOwnerAndId(owner, carId);
        return EntityUtils.createCarValueObject(car);
    }

    @Transactional
    public void saveCar(Car car) throws InvalidEntityException {
        carValidator.validate(car);
        carDAO.save(car);
    }

    @Transactional
    public void removeCarById(Long id) {
        Car car = carDAO.findById(id);
        carDAO.remove(car);
    }
}
